import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'normalize.css'

Vue.config.productionTip = false

try {
  // let socket = null;


  let ws = new Vue({
    data() {
      return {
        log: '',
        socket: null,
        port: '',
      }
    },
    methods: {
      send(x) {
        this.socket.send(x)
      },
      connect() {
        const that = this

        this.log = '后台连接中...'
        this.socket = new WebSocket(`ws://localhost:${this.port}`)

        this.socket.addEventListener('open', function (event) {
          that.socket.send('jnbjt');
        });
      
        this.socket.addEventListener('message', function (event) {
          that.log = event.data
        });

        that.socket.addEventListener('close', this.tryReconnect)

        that.socket.addEventListener('error', this.tryReconnect)
      },
      tryReconnect() {
        let count = 5;
        let task = setInterval(() => {
          this.log = `连接失败, ${count} 秒后尝试重连`;
          count -= 1;
        }, 1000)
        setTimeout(() => {
          this.connect();
          clearInterval(task)
        }, count * 1000)
      },
      listen(p) {
        this.port = p || '1234'
        console.log(`listen ${this.port} ...`)
        this.connect()
      }
    }
  })

  

  Vue.prototype.$ws = ws
}
catch (e) {
  console.error(e)
}

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')


